package com.jonluo.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jonluo.common.utils.*;
import com.jonluo.entity.UserEntity;
import com.jonluo.entity.UserRoleEntity;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 * @author com.jonluo
 * Date 2017/9/15
 */
@RestController
@RequestMapping("/sys/user")
public class UserController extends AbstractController {

	@Autowired
	RestTemplate restTemplate;
	@Autowired
	EnvVariable envVariable;
	
	/**
	 * 所有用户列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R list(@RequestParam Map<String, Object> params){
		JSONObject json = new JSONObject();
		JSONObject para = new JSONObject();
		json.put("page",params.get("page"));
		json.put("limit",params.get("limit"));
		para.put("username",params.get("username"));
		json.put("params",para);
		String resultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/user/getAll",json, String.class).getBody();
		JSONObject resultMap = JSONObject.parseObject(resultJson);
		if ( 0 == resultMap.getInteger("code")){
			PageUtils pageUtil = new PageUtils(resultMap.getJSONArray("data"),resultMap.getInteger("total"),json.getInteger("limit"),json.getInteger("page") );
			return R.ok().put("page", pageUtil);
		}else {
			return R.ok().put("page",  new PageUtils());
		}

	}
	
	/**
	 * 获取登录的用户信息
	 */
	@RequestMapping("/info")
	public R info(){
		return R.ok().put("user", getCurrentUser());
	}
	
	/**
	 * 修改登录用户密码
	 */
	@RequestMapping("/password")
	public R password(String password, String newPassword){
		Assert.isBlank(newPassword, "新密码不为能空");
		//sha256加密
		password = new Sha256Hash(password, getCurrentUser().getSalt()).toHex();
		//sha256加密
		newPassword = new Sha256Hash(newPassword, getCurrentUser().getSalt()).toHex();
		JSONObject json = new JSONObject();
		json.put("userId",getCurrentUserId());
		json.put("password",password);
		json.put("newPassword",newPassword);
		String resultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/user/updatePassword",json, String.class).getBody();
		JSONObject resultMap = JSONObject.parseObject(resultJson);
		if(0 != resultMap.getInteger("code")){
			return R.error("原密码不正确");
		}
		return R.ok();
	}
	
	/**
	 * 用户信息
	 */
	@RequestMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") String userId){
		UserEntity user = null ;
		String resultJson = restTemplate.getForEntity(envVariable.getBaseUrl()+"/user/getById/"+userId, String.class).getBody();
		JSONObject resultMap = JSONObject.parseObject(resultJson);
		if ( 0 == resultMap.getInteger("code")){
			user = resultMap.getObject("data",UserEntity.class);
		}else {
			user = new UserEntity();
		}
		//查询角色
		JSONObject json = new JSONObject();
		JSONObject para = new JSONObject();
		para.put("userId",userId);
		json.put("params",para);
		resultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/userRole/getAll",json, String.class).getBody();
		//获取用户所属的角色列表
		resultMap = JSONObject.parseObject(resultJson);
		JSONArray roleList  = resultMap.getJSONArray("data");
		List<String> roleIdList = new ArrayList<String>();
		for (int i = 0;i < roleList.size();i++){
			UserRoleEntity r  = JSONObject.parseObject(roleList.getJSONObject(i).toJSONString(),UserRoleEntity.class);
			roleIdList.add(r.getRoleId()+"");
		}
		user.setRoleIdList(roleIdList);
		return R.ok().put("user", user);
	}
	
	/**
	 * 保存用户
	 */
	@RequestMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R save(@RequestBody UserEntity user){
		user.setUserId(UuidUtils.getUUID("user"));
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		String resultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/user/add",user, String.class).getBody();
		JSONObject resultMap = JSONObject.parseObject(resultJson);
		//保存用户与角色关系
		int i = userRoleSaveOrUpdate(user.getUserId(), user.getRoleIdList());
		if(0 == resultMap.getInteger("code") && i == 0){
			return R.ok("success");
		}else {
			return R.error("fail");
		}
	}
	
	/**
	 * 修改用户
	 */
	@RequestMapping("/update")
	@RequiresPermissions("sys:user:update")
	public R update(@RequestBody UserEntity user){
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			//sha256加密
			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
		}
		String resultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/user/update",user, String.class).getBody();
		JSONObject resultMap = JSONObject.parseObject(resultJson);
		//保存用户与角色关系
		int i = userRoleSaveOrUpdate(user.getUserId(), user.getRoleIdList());
		if(0 == resultMap.getInteger("code") && i == 0){
			return R.ok("success");
		}else {
			return R.error("fail");
		}
	}
	
	/**
	 * 删除用户
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody String[] userIds){
		if(ArrayUtils.contains(userIds, envVariable.getSuperAdminId())){
			return R.error("超级管理员不能删除");
		}
		JSONObject json = new JSONObject();
		json.put("userIds",StringUtils.join(userIds, ","));
		String resultJson = restTemplate.postForEntity(envVariable.getBaseUrl()+"/user/deleteByIds",json, String.class).getBody();
		restTemplate.postForEntity(envVariable.getBaseUrl()+"/userRole/deleteByUserIdsOrRoleIds",json, String.class);
		JSONObject resultMap = JSONObject.parseObject(resultJson);
		if(0 == resultMap.getInteger("code")){
			return R.ok("success");
		}else {
			return R.error("fail");
		}

	}


	public int userRoleSaveOrUpdate(String userId, List<String> roleIdList) {
		    JSONObject json = new JSONObject();
		    json.put("userIds",userId);
			//先删除用户与角色关系
		    String resultJson =restTemplate.postForEntity(envVariable.getBaseUrl()+"/userRole/deleteByUserIdsOrRoleIds",json, String.class).getBody();
		    JSONObject resultMap = JSONObject.parseObject(resultJson);
		    //保存用户与角色关系
		    if(roleIdList.size() > 0 && resultMap.getInteger("code") == 0) {
				List<UserRoleEntity> list = new ArrayList<UserRoleEntity>();
				UserRoleEntity userRole = null;
				for (int i = 0; i < roleIdList.size(); i++) {
					userRole = new UserRoleEntity();
					userRole.setId(UuidUtils.getUUID("userRole"));
					userRole.setRoleId(roleIdList.get(i));
					userRole.setUserId(userId);
					list.add(userRole);
				}
				json.put("list", list);
				resultJson = restTemplate.postForEntity(envVariable.getBaseUrl() + "/userRole/addBatch", json, String.class).getBody();
				resultMap = JSONObject.parseObject(resultJson);
			}
		    return resultMap.getInteger("code") ;
	}
}
